<?php
	include_once('../include/init.php');
	include_once(dirname(dirname(__FILE__)).'/include/global_function.php'); //绝对路径
	$act = !empty($_GET['act'])?$_GET['act']:'list';
	$db = new News();
	$db_q = new Type_q();
	if(!empty($_POST)){
		if(!empty($_FILES)){
			$_POST['img'] = upload($_FILES['img']);
			//print_r($_POST['img']);exit;
		}
		else{
		$_POST['img'] = '';
		}
		$title = $_POST['title'];
		$content = $_POST['content'];
	}
	switch($act)
	{
		case 'list':
		//include_once(dirname(__FILE__). '/'. '../include/global_function.php');
			//分页三要素：总记录、每页显示条数、当前页码
			$p = (isset($_GET['p']))? $_GET['p'] : 1;  //获取当前页
			$pagenum = 5;   //每页显示3条
			$pagelink = page('news.php','12_news',$p, $pagenum);   //分页变量调用了全局的分页函数并传实际参数
			
			//如果有关键字就是关键字查询，否则无条件查询 
			//获取关键字
			//$keywords = (isset($_GET['keywords']))? $_GET['keywords'] : '';
			//limit 起始的下标,输出的条数(最少为0，不能是负数)
			//limit 0,3 从下标为0的一条开始，获取3条
			//offset = (p-1)*$pagenum;
			$offset = ($p - 1)*$pagenum; 
		$joinArr = array(
			'join'=>'left',
			'tab'=>'12_type',
			'left_on'=>'type_id',
			'right_on'=>'id'
		);
		
		$db->where = array();
		$db->sel = '12_news.*,12_type.id as t_id,12_type.name as t_name';
		$db->join=$joinArr;
		$db->offset=$offset;
		$db->limit=$pagenum;		
		$list = $db->getList();
		//print_r($list);exit;
		
		if(!empty($_GET['ajax'])){
			$data = array(
				'result'=>$list,
				'page'=>$pagelink
			);
			echo json_encode($data);
		}
		else{
			include_once('templates/news.php');
		}
		
		break;
		//添加 add
		
		case 'add':
			if(!empty($_POST)){
				//print_r($_POST);exit;
				if($db->create($_POST)){
					echo ('<script>
							alert("添加成功！");
							window.location = "news.php";
						</script>');
				}
				else{
					die('查询出错，原因：'.mysql_error());
				}
				exit;
			}
			$top = $db_q->getTreeTop();
			//print_r($top);exit;
			include_once('templates/news_add.php');
		break;
		case 'getLevel':
			$pid =!empty($_GET['pid'])?$_GET['pid']:0;
			$levelList = $db_q->getTreeTop($pid);
		
			echo json_encode($levelList);
			

		break;
		
		//修改
		case 'edi':
		if(!empty($_POST)){
		//print_r($_POST);exit;
			$id = $_POST['id'];
			if($db->update($_POST)){
				echo ('<script>
							alert("修改成功！");
							window.location = "news.php";
						</script>');
			}
			exit;
		}
		$id = !empty($_GET['id'])?$_GET['id']:0;//获取Id
		$db->where = array('id'=>$id);
		$result = $db->getOne();
		include_once('templates/news_edit.php');
		break;
		
		//删除
		case 'del':
		$id = !empty($_GET['id'])?$_GET['id']:0;
		if(! $id || ''==$id){
			die('
				<script>
					alert("id参数有误！")
					window.history.back();
				<script/>
			');
		}
		$sql = 'delete from `12_news` where `id`="'.$id.'"';
		$query = mysql_query($sql);
		if(!$query){
			die('执行失败：'.mysql_error());
		}
		else{
			die('<script>
						alert("删除成功！");
						window.history.back();
				     </script>');
		}
		break;
		default:
			echo "参数错误";
	}

?>
